<?php

namespace maotool\view\template;

use maotool\object\ReflectionUtil;
use maotool\object\StrUtil;
use maotool\script\PhpScriptUtil;
use maotool\view\html\Document;
use maotool\view\html\Element;

/**
 * 处理标签
 */
class TemplateTagProcessor
{

    /**
     * 加载元素
     * @param $element
     * @param $params
     * @return string
     */
    public function loadElement($element, $params)
    {
        if ($element["nodeName"] == "#text") {
            $nodeName = "sharpText";
        } else {
            $nodeName = $element["nodeName"];
        }
        $nodeName = "tag" . StrUtil::upperFirst($nodeName);
        return call_user_func(array($this, $nodeName), $element, $params);
    }

    /**
     * 遍历元素
     * @param $childNodes
     * @param $params
     * @return array
     */
    public function loadNodes($childNodes, $params)
    {
        foreach ($childNodes as $childNode) {
            $this->loadElement($childNode, $params);
        }
        return $childNodes;
    }

    /**
     * 加载替换Sql中的参数
     * @param $text
     * @param $params
     * @return string
     */
    private function loadVar($text, $params)
    {
        $text = StrUtil::format($text, $params, function ($match, $params) use (&$vars) {
            return addslashes(PhpScriptUtil::expression($match, $params));
        });
        return StrUtil::format($text, $params, function ($match, $params) use (&$vars) {
            return PhpScriptUtil::expression($match, $params);
        }, '\${', "}");
    }

    /**
     * 加载属性
     * @return void
     */
    private function loadAttribute()
    {

    }

    /**
     * @param Element|Document $element
     * @param array|null $params
     * @return Element|Document
     */
    public function tag($element, $params)
    {
        if (count($element->children)) {
            $this->loadNodes($element->children, $params);
        }
        return $element;
    }

}